package com.hcy.app.screen.relax

import android.Manifest.permission.READ_MEDIA_VIDEO
import android.content.pm.PackageManager.PERMISSION_GRANTED
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import coil.ImageLoader
import coil.compose.rememberAsyncImagePainter
import coil.decode.SvgDecoder
import coil.request.ImageRequest
import coil.size.Size
import com.hcy.app.LocalNavController
import com.hcy.app.R
import kotlinx.coroutines.launch


@Preview
@Composable
fun Home_Page_Pre(){
    Relax_Home()
}

@Composable
fun Relax_Home(
    viewModel: RelaxViewModel = hiltViewModel(LocalContext.current as ComponentActivity)
){
    val ctx = LocalContext.current
    val relaxState by viewModel.relaxState.collectAsState()
    var showPrivate by remember { mutableStateOf(false) }
    var showPwdDialog by remember { mutableStateOf(false) }
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    // 创建权限启动器
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = {
        }
    )
    LaunchedEffect(Unit){
        // 某次系统更新后 READ_MEDIA_AUDIO 就需要动态授权了。
        // mainfest 直接写权限后还需要动态权限，每次系统更新貌似都需要重新授权，莫名其妙！
        if (ContextCompat.checkSelfPermission(ctx, READ_MEDIA_VIDEO.toString()) != PERMISSION_GRANTED) {
            permissionLauncher.launch(READ_MEDIA_VIDEO.toString()) // 自动弹出权限请求对话框
        }
    }

    Column(
        modifier = Modifier.fillMaxSize().
        background(Color(0xffdcd2d4)).
        systemBarsPadding()
    ) {

        if ( showPwdDialog ){
            PasswordDialog(
                onDismiss={ showPwdDialog = false},
                onConfirm={pwd ->
                    if ( pwd == relaxState.privatePwd ){
                        showPwdDialog = false
                        showPrivate = true
                    }else{
                        scope.launch {
                            snackbarHostState.showSnackbar("密码不正确")
                        }
                    }
                }
            )
        }
        Book_Tool(onDialogChange={it->
            showPwdDialog = it
        })

        var fileList = listOf<RelaxFileInfo>()
        if (showPrivate){
            fileList = relaxState.fileList.filter { it.isPrivate }
        }else{
            fileList = relaxState.fileList.filter { !it.isPrivate }
        }

        fileList.forEach { it->
            File_Item(it)
        }
    }
}

@Composable
internal fun File_Item(info: RelaxFileInfo,viewModel: RelaxViewModel = hiltViewModel(LocalContext.current as ComponentActivity)){
    val navController = LocalNavController.current
    val context = LocalContext.current
    Row(
        verticalAlignment = Alignment.CenterVertically, // 添加这行
        modifier = Modifier.fillMaxWidth()
            .border(width = 1.dp, color = Color.Cyan,shape = RoundedCornerShape(1.dp))
            .padding(2.dp).clickable{
                viewModel.setCurrentFile(info)
                when(info.fileType){
                    "txt","log" ->navController.navigate("relax/book")
                    "mp4" ->navController.navigate("relax/video")
                }
            }
    ) {
        // 创建支持 SVG 的 ImageLoader
        val imageLoader = ImageLoader.Builder(context)
            .components {
                add(SvgDecoder.Factory())
            }
            .build()
        Image(
            painter = rememberAsyncImagePainter(
                model = ImageRequest.Builder(context)
                    .data(if ( info.fileType=="txt" )R.drawable.book else R.drawable.video) // 或使用 raw 资源
                    .size(Size.ORIGINAL) // 保持原始尺寸
                    .build(),
                imageLoader = imageLoader
            ),
            contentDescription = "图片描述", // 用于无障碍访问
            modifier = Modifier.size(50.dp),
            colorFilter = ColorFilter.tint(
                color = Color.Cyan, // 设置你想要的颜色
                blendMode = BlendMode.SrcIn // 关键参数，保留透明度
            )
        )
        Text(info.name)
        // 使用Spacer填充剩余空间,将IconButton挤过去
        Spacer(modifier = Modifier.weight(1f))
        IconButton(
            content ={
                Icon(
                    imageVector =  ImageVector.vectorResource(id =  if ( info.isPrivate ) R.drawable.show else R.drawable.hide),
                    contentDescription = "私有/公开",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {
                // 修改文件是否为私有
                viewModel.updateShow(info.id,!info.isPrivate)
            }
        )
        IconButton(
            content ={
                Icon(
                    imageVector =  Icons.Default.Delete,
                    contentDescription = "删除",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {
                // 修改文件是否为私有
                viewModel.updateShow(info.id,!info.isPrivate)
            }
        )
    }
}

@Composable
internal fun PasswordDialog(
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit
){
    val password = remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("输入密码") },
        text = {
            TextField(
                value = password.value,
                onValueChange = { password.value = it },
                label = { Text("密码") },
                visualTransformation = PasswordVisualTransformation(), // 密码隐藏
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
            )
        },
        confirmButton = {
            TextButton(
                onClick = { onConfirm(password.value) }
            ) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(
                onClick = onDismiss
            ) {
                Text("取消")
            }
        }
    )

}
@Composable
fun Book_Tool(
    viewModel: RelaxViewModel = hiltViewModel(),
    onDialogChange:(Boolean) -> Unit,
){
    val navController = LocalNavController.current
    val ctx = LocalContext.current
    // 工具栏
    Row(
        modifier = Modifier.fillMaxWidth()
            .zIndex(2f)
            .background(Color(0xFF96D306)),
        horizontalArrangement = Arrangement.End,
    ) {
        IconButton(
            content ={
                Icon(
                    imageVector = Icons.Default.Home,
                    contentDescription = "首页",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {
                navController.navigate("home")
            }
        )
        IconButton(
            content ={
                Icon(
                    imageVector = ImageVector.vectorResource(id = R.drawable.wifi),
                    contentDescription = "wifi传输",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {}
        )
        IconButton(
            content ={
                Icon(
                    imageVector = Icons.Default.Refresh,
                    contentDescription = "刷新列表",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {
                viewModel.reloadFileList(ctx)
            }
        )
        IconButton(
            content ={
                Icon(
                    imageVector = ImageVector.vectorResource(id = R.drawable.lock),
                    contentDescription = "私有文件",
                    tint = Color.White,
                    modifier = Modifier.size(30.dp)
                )
            },
            onClick = {
                onDialogChange(true)
//                showPwdDialog = true
            }
        )
    }


}

